//
//  LoginViewController.swift
//  fho
//
//  Created by 郭颢源 on 2021/4/29.
//

import UIKit

class LoginViewController: UITableViewController {
    
    //用户名、密码
    private var userTextField: UITextField!
    private var passwordTextField: UITextField!
    //操作按钮
    private var nextButton: UIButton!
    
    //闭包
    typealias ReturnClosure = (_ isSuccess: Bool) -> Void
    //回调
    var loginSuccess: ReturnClosure?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.isHidden = true


        // Do any additional setup after loading the view.
//        self.title = "登录"
        
        //自定义navBar样式
        self.naviBarStyle()
        //创建视图
        initViews()
    }
    
    // MARK: - Custom Methods
    
    private func initViews() -> Void {
        
        //修改tableView样式
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor.white
        //tableView的headerView
        thView()
        //tableView的footerView
        tfView()
    }
    
    private func thView() -> Void {
        
        //说明
        let infoLabel = UILabel(frame: CGRect(x: NSKVar.kLR20, y: 0.0, width: NSKVar.kScreenWidth - 2.0 * NSKVar.kLR20,
                                              height: 124.0))
        infoLabel.font = UIFont.systemFont(ofSize: 22.0)
        infoLabel.numberOfLines = 0
        infoLabel.text = "你好，" + "\n" + "欢迎来到优惠购"
        //用户名
        let hTextField: CGFloat = 54.0
        userTextField = textField(with: CGRect(x: NSKVar.kLR20, y: infoLabel.frame.maxY, width: infoLabel.frame.size.width,height: hTextField),placeholder: "请输入您的手机号", keyboardType: .numberPad)
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: NSKVar.kLR20, y: userTextField.frame.maxY, width: infoLabel.frame.size.width,
                                 height: 0.5)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //密码
        passwordTextField = textField(with: CGRect(x: NSKVar.kLR20, y: lineLayer.frame.maxY,
                                                   width: infoLabel.frame.size.width,
                                                   height: hTextField),
                                      placeholder: "请输入您的密码", isSecure: true, returnKeyType: .go)
        //tableView的headerView
        let tbhView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: passwordTextField.frame.maxY))
        //添加
        tbhView.addSubview(infoLabel)
        tbhView.addSubview(passwordTextField)
        tbhView.addSubview(userTextField)
        //标题
        userTitle()
        passwordTitle("密码", to: passwordTextField)
        //设置
        self.tableView.tableHeaderView = tbhView
        
        
//        tbhView.showSubviews()
        userTextField.text = "17337107036"
        passwordTextField.text = "123456"

    }
    
    private func userTitle() -> Void {
        
        let hVal: CGFloat = 0.4 * userTextField.frame.size.height
        //手机区号
        let wLabel: CGFloat = 64.0
        let zoneLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: wLabel, height: hVal))
        zoneLabel.font = userTextField.font
        zoneLabel.attributedText = userAttrText()
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: zoneLabel.frame.maxX, y: 0.0, width: 1.0, height: hVal)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //用户名称标题视图
        let wVal: CGFloat = 84.0
        let tempView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: wVal, height: hVal))
        //添加
        tempView.addSubview(zoneLabel)
        tempView.layer.addSublayer(lineLayer)
        //设置
        userTextField.leftView = tempView
        userTextField.leftViewMode = .always
    }
    
    private func passwordTitle(_ title: String, to textField: UITextField) -> Void {
        
        let hVal: CGFloat = 0.4 * userTextField.frame.size.height
        //手机区号
        let wLabel: CGFloat = 64.0
        let zoneLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: wLabel, height: hVal))
        zoneLabel.font = userTextField.font
        zoneLabel.text = title
        //用户名称标题视图
        let wVal: CGFloat = 84.0
        let tempView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: wVal, height: hVal))
        //添加
        tempView.addSubview(zoneLabel)
        //设置
        textField.leftView = tempView
        textField.leftViewMode = .always
    }
    
    private func tfView() -> Void {
        
        //注册
        let wLabel: CGFloat = 64.0
        let hLabel: CGFloat = 54.0
        let registerLabel = UILabel(frame: CGRect(x: userTextField.frame.maxX - wLabel, y: 0.0, width: wLabel,
                                                  height: hLabel))
        registerLabel.font = UIFont.systemFont(ofSize: 12.0)
        registerLabel.textAlignment = .right
        registerLabel.textColor = NSKVar.C9_COLOR
        registerLabel.text = "账号注册?"
        registerLabel.isUserInteractionEnabled = true
        //添加事件
        let tempRecognizer = UITapGestureRecognizer(target: self, action: #selector(registerRecognizer(_:)))
        registerLabel.addGestureRecognizer(tempRecognizer)
        //按钮
        let hButton: CGFloat = 50.0
        nextButton = "登录".button(with: CGRect(x: NSKVar.kLR20, y: registerLabel.frame.maxY + NSKVar.kLR10,
                                                  width: userTextField.frame.size.width,
                                                  height: hButton),
                                     target: self, action: #selector(nextButtonTouched(_:)))
        //tableView的footView
        let tbfView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: nextButton.frame.maxY))
        //添加
        tbfView.addSubview(nextButton)
        tbfView.addSubview(registerLabel)
        //设置
        self.tableView.tableFooterView = tbfView
    }
    
    @objc private func registerRecognizer(_ sender: UITapGestureRecognizer) -> Void {
        
        //注册
        let viewController = RegisterViewController()
        self.navigationController?.pushViewController(viewController, animated: true)
    }
    
    @objc private func nextButtonTouched(_ sender: UIButton) -> Void {
        
        //关闭键盘
        passwordTextField.resignFirstResponder()
        userTextField.resignFirstResponder()
        //用户名是否为空？
        let accountVal = userTextField.text ?? ""
        if "" == accountVal {
            UIKToastView.showText("请输入您的手机号码")
            return
        }
        if true != accountVal.regularPhone() {
            UIKToastView.showText("请输入正确的手机号码")
            return
        }
        //密码是否为空？
        let passwordVal = passwordTextField.text ?? ""
        if "" == passwordVal {
            UIKToastView.showText("请输入您的密码")
            return
        }
        //请求登录
        loginRequest()
    }
    
    @objc private func endOnExit(_ sender: UITextField) -> Void {
        
        //关闭键盘
        sender.resignFirstResponder()
        //是否为确认密码？
        if sender.isEqual(passwordTextField) {
            loginRequest()
        }
    }
    
    private func userAttrText() -> NSAttributedString {
        
        //图片大小
        let szImg = CGSize(width: 10.0, height: 10.0)
        let attachment = NSTextAttachment()
        attachment.bounds = CGRect(origin: CGPoint(x: 0.0, y: -1.0), size: szImg)
        attachment.image = UIImage(named: "system_arrow_down_gray")
        //值
        let tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: "+86  "))
        tempVal.append(NSAttributedString(attachment: attachment))
        //返回
        return tempVal
    }
    
    private func textField(with frame: CGRect, placeholder: String,
                           isSecure: Bool = false, keyboardType: UIKeyboardType = .default,
                           returnKeyType: UIReturnKeyType = .done) -> UITextField {
        
        //创建
        let tempTextField = UITextField(frame: frame)
        tempTextField.borderStyle = .none
        tempTextField.font = UIFont.systemFont(ofSize: 16.0)
        tempTextField.placeholder = placeholder
        tempTextField.isSecureTextEntry = isSecure
        tempTextField.clearButtonMode = .whileEditing
        tempTextField.keyboardType = keyboardType
        tempTextField.returnKeyType = returnKeyType
        tempTextField.addTarget(self, action: #selector(endOnExit(_:)), for: .editingDidEndOnExit)
        //分隔线
        let lineLayer = CALayer()
        lineLayer.frame = CGRect(x: 0.0, y: frame.size.height, width: frame.size.width, height: 0.5)
        lineLayer.backgroundColor = NSKVar.SEPERATOR_COLOR.cgColor
        //添加
        tempTextField.layer.addSublayer(lineLayer)
        //返回
        return tempTextField
    }
    
    private func updateData(_ resData: Dictionary<String, Any>) -> Void {
        
        //隐藏等待
        //        self.showWaitting(false)
        
        //解析数据
        var tempData = resData
        //是否记住密码？
        tempData["password"] = self.passwordTextField.text!
        tempData["isLogined"] = 1
        //更新保存
        let tempObj = NSKUserInfo.shared
        tempObj.loginUser = tempData.toModel(NSKLoginUserModel.self)
        tempObj.save()
        //回调是否为空？
        if let returnClosure = self.loginSuccess {
            returnClosure(true)
        }
        let tabarController = RootViewController()
        
        UIApplication.shared.windows.first?.rootViewController = tabarController
    }
    
    private func loginRequest() -> Void {
        
        //请求参数
        let params = ["mobile": userTextField.text!,
                        "password": passwordTextField.text!]
        self.showWaiting()
        self.requestObj.requestTarget(NSKMoyaAPI.login(params: params), with: { [unowned self] (resObj: Any?) in
            //结果
            var resultData: Dictionary<String, Any> = [:]
            //是否有数据？
            if let tempData = resObj as? Dictionary<String, Any> {
                resultData = tempData
            }
            self.updateData(resultData)
            
        }) { (cde: NSKResponseCode, msg: String) in
            //隐藏等待
            self.showWaiting(false)
        }
    }
}
